// Chrome扩展内容脚本 - 在小红书页面中注入
console.log('小红书助手内容脚本已注入')

// 检查是否在小红书网站
if (window.location.hostname.includes('xiaohongshu.com')) {
  initXhsHelper()
}

function initXhsHelper() {
  console.log('初始化小红书助手功能')
  
  // 创建助手按钮
  createHelperButton()
  
  // 监听页面变化
  observePageChanges()
  
  // 自动分析内容
  autoAnalyzeContent()
}

// 创建浮动助手按钮
function createHelperButton() {
  // 检查是否已存在按钮
  if (document.getElementById('xhs-helper-btn')) return
  
  const button = document.createElement('div')
  button.id = 'xhs-helper-btn'
  button.innerHTML = `
    <div style="
      position: fixed;
      top: 50%;
      right: 20px;
      z-index: 10000;
      width: 60px;
      height: 60px;
      background: linear-gradient(135deg, #ff6b6b, #ee5a24);
      border-radius: 50%;
      box-shadow: 0 4px 20px rgba(238, 90, 36, 0.3);
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      color: white;
      transition: all 0.3s ease;
      user-select: none;
    " title="小红书助手">
      🌹
    </div>
  `
  
  // 添加悬停效果
  button.addEventListener('mouseenter', () => {
    button.style.transform = 'scale(1.1)'
  })
  
  button.addEventListener('mouseleave', () => {
    button.style.transform = 'scale(1)'
  })
  
  // 点击事件
  button.addEventListener('click', () => {
    showHelperPanel()
  })
  
  document.body.appendChild(button)
}

// 显示助手面板
function showHelperPanel() {
  // 检查是否已存在面板
  let panel = document.getElementById('xhs-helper-panel')
  
  if (panel) {
    panel.style.display = panel.style.display === 'none' ? 'block' : 'none'
    return
  }
  
  // 创建面板
  panel = document.createElement('div')
  panel.id = 'xhs-helper-panel'
  panel.innerHTML = `
    <div style="
      position: fixed;
      top: 50%;
      right: 100px;
      transform: translateY(-50%);
      z-index: 10001;
      width: 300px;
      background: white;
      border-radius: 12px;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
      padding: 20px;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    ">
      <div style="
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        padding-bottom: 12px;
        border-bottom: 1px solid #eee;
      ">
        <h3 style="margin: 0; color: #333; font-size: 18px;">🌹 小红书助手</h3>
        <span id="close-panel" style="
          cursor: pointer;
          font-size: 20px;
          color: #999;
        ">×</span>
      </div>
      
      <div style="margin-bottom: 16px;">
        <button id="analyze-btn" style="
          width: 100%;
          padding: 12px;
          background: #409eff;
          color: white;
          border: none;
          border-radius: 6px;
          cursor: pointer;
          font-size: 14px;
          margin-bottom: 8px;
        ">📊 分析当前内容</button>
        
        <button id="tags-btn" style="
          width: 100%;
          padding: 12px;
          background: #67c23a;
          color: white;
          border: none;
          border-radius: 6px;
          cursor: pointer;
          font-size: 14px;
          margin-bottom: 8px;
        ">🏷️ 生成智能标签</button>
        
        <button id="export-btn" style="
          width: 100%;
          padding: 12px;
          background: #e6a23c;
          color: white;
          border: none;
          border-radius: 6px;
          cursor: pointer;
          font-size: 14px;
        ">📋 导出数据</button>
      </div>
      
      <div id="result-area" style="
        max-height: 200px;
        overflow-y: auto;
        padding: 12px;
        background: #f8f9fa;
        border-radius: 6px;
        font-size: 13px;
        color: #666;
        display: none;
      "></div>
    </div>
  `
  
  document.body.appendChild(panel)
  
  // 绑定事件
  document.getElementById('close-panel').addEventListener('click', () => {
    panel.style.display = 'none'
  })
  
  document.getElementById('analyze-btn').addEventListener('click', analyzeCurrentContent)
  document.getElementById('tags-btn').addEventListener('click', generateTags)
  document.getElementById('export-btn').addEventListener('click', exportData)
}

// 分析当前内容
function analyzeCurrentContent() {
  const resultArea = document.getElementById('result-area')
  resultArea.style.display = 'block'
  resultArea.innerHTML = '🔄 正在分析内容...'
  
  // 获取页面内容
  const content = extractPageContent()
  
  // 发送消息给后台脚本
  chrome.runtime.sendMessage({
    action: 'analyzeContent',
    data: content
  }, (response) => {
    if (response?.success) {
      const { data } = response
      resultArea.innerHTML = `
        <div><strong>📈 分析结果:</strong></div>
        <div>情感倾向: ${data.sentiment === 'positive' ? '😊 积极' : '😐 中性'}</div>
        <div>内容评分: ${data.score}/100</div>
        <div>关键词: ${data.keywords.join(', ')}</div>
        <div><strong>💡 优化建议:</strong></div>
        <ul style="margin: 8px 0; padding-left: 16px;">
          ${data.suggestions.map(s => `<li>${s}</li>`).join('')}
        </ul>
      `
    } else {
      resultArea.innerHTML = '❌ 分析失败，请重试'
    }
  })
}

// 生成智能标签
function generateTags() {
  const resultArea = document.getElementById('result-area')
  resultArea.style.display = 'block'
  resultArea.innerHTML = '🔄 正在生成标签...'
  
  // 获取页面内容
  const content = extractPageContent()
  
  // 发送消息给后台脚本
  chrome.runtime.sendMessage({
    action: 'generateTags',
    data: content
  }, (response) => {
    if (response?.success) {
      const { data } = response
      resultArea.innerHTML = `
        <div><strong>🏷️ 推荐标签:</strong></div>
        <div style="margin-top: 8px;">
          ${data.tags.map(tag => `
            <span style="
              display: inline-block;
              background: #409eff;
              color: white;
              padding: 4px 8px;
              border-radius: 4px;
              font-size: 12px;
              margin: 2px;
              cursor: pointer;
            " onclick="copyToClipboard('${tag}')">${tag}</span>
          `).join('')}
        </div>
        <div style="margin-top: 8px; font-size: 12px; color: #999;">
          点击标签复制到剪贴板
        </div>
      `
    } else {
      resultArea.innerHTML = '❌ 生成失败，请重试'
    }
  })
}

// 导出数据
function exportData() {
  const resultArea = document.getElementById('result-area')
  resultArea.style.display = 'block'
  resultArea.innerHTML = '🔄 正在导出数据...'
  
  // 获取页面数据
  const data = {
    url: window.location.href,
    title: document.title,
    content: extractPageContent(),
    timestamp: new Date().toISOString()
  }
  
  // 创建下载链接
  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `xhs-data-${Date.now()}.json`
  a.click()
  URL.revokeObjectURL(url)
  
  resultArea.innerHTML = '✅ 数据已导出到下载文件夹'
}

// 提取页面内容
function extractPageContent() {
  const title = document.title || ''
  const description = document.querySelector('meta[name="description"]')?.content || ''
  const content = document.body.innerText.slice(0, 1000) // 限制长度
  
  return {
    title,
    description,
    content,
    url: window.location.href
  }
}

// 复制到剪贴板
function copyToClipboard(text) {
  navigator.clipboard.writeText(text).then(() => {
    // 显示复制成功提示
    showToast('已复制到剪贴板: ' + text)
  })
}

// 显示提示消息
function showToast(message) {
  const toast = document.createElement('div')
  toast.textContent = message
  toast.style.cssText = `
    position: fixed;
    top: 20px;
    right: 20px;
    z-index: 10002;
    background: rgba(0, 0, 0, 0.8);
    color: white;
    padding: 12px 16px;
    border-radius: 6px;
    font-size: 14px;
    max-width: 300px;
  `
  
  document.body.appendChild(toast)
  
  setTimeout(() => {
    document.body.removeChild(toast)
  }, 3000)
}

// 监听页面变化
function observePageChanges() {
  const observer = new MutationObserver((mutations) => {
    // 页面内容变化时的处理逻辑
    console.log('页面内容发生变化')
  })
  
  observer.observe(document.body, {
    childList: true,
    subtree: true
  })
}

// 自动分析内容
function autoAnalyzeContent() {
  // 延迟执行，等待页面完全加载
  setTimeout(() => {
    chrome.storage.local.get(['config'], (result) => {
      if (result.config?.autoAnalyze) {
        console.log('自动分析内容功能已启用')
        // 在这里可以添加自动分析逻辑
      }
    })
  }, 3000)
} 